<script setup>
import { reactive, ref, onBeforeUnmount, onMounted, watch, nextTick } from 'vue';
import { ElDivider, ElRadio, ElRadioGroup } from 'element-plus';
import { storeToRefs } from 'pinia';
import mitt from '@/common/common-helper';
import { useMapStore } from '@/stores';
import MapAttribute from './MapAttribute.vue';
import MapPoints from './MapPoints.vue';
import {
  CLEAR_POPUP_MAP,
  MAP_2D_INIT,
  MEASURE_AREA_V,
  MEASURE_CLEAR,
  MEASURE_CLEAR_V,
  MEASURE_LINE_V,
  MEASURE_POINT,
  REMOVE_2D_MAP,
  REMOVE_LAYER,
  REMOVE_MAP_IMG,
  TOGGLE_2D_SOURCE,
} from './common/common-map-fun';
import { layerGroupId, presetSource } from './common/common-map-info';
import MapRecordIndex from './map-record/index.vue';

let map = null;
const storeMap = useMapStore();
const { visibleLayers, initialized, mapOnClick } = storeToRefs(storeMap);

const windowShow = ref(false);
const useChecked = ref('');

const resultFeatures = ref(null);

const videoPointAll = ref([]);
const checkedVideo = ref({});
const videoDialogVisible = ref(false);

const state = reactive({
  map_use_type: '',
  map_measure_type: '',
  map_layer_active_name: '',
});

const icon_map = reactive({
  icon_3D: new URL('../../assets/images/icon/3D.png', import.meta.url).href,
  XHGL_icon: new URL('../../assets/images/icon/巡护管理.png', import.meta.url).href,
  SJGL_icon: new URL('../../assets/images/icon/事件管理.png', import.meta.url).href,
  SSXC_icon: new URL('../../assets/images/icon/实时巡查.png', import.meta.url).href,
});

watch(
  initialized,
  (val) => {
    if (!visibleLayers.value.has(presetSource.RASTER[0]._id)) {
      handleToggle(presetSource.RASTER[0], val);
    }

    if (!visibleLayers.value.has(presetSource.RASTER[1]._id)) {
      handleToggle(presetSource.RASTER[1], val);
    }
  },
  { deep: true },
);

onMounted(() => {
  nextTick(() => {
    if (!map) {
      map = MAP_2D_INIT('map-data-center');

      window.addEventListener('resize', resize2D);
    }
  });
});

function resize2D() {
  map?.resize();
}

// 底图
function handleToggle(source, init) {
  if (init.includes('2d')) {
    const { _id, _group, ...mapboxSource } = source;

    TOGGLE_2D_SOURCE(mapboxSource, { id: _id, group: _group });
  }

  storeMap.TOGGLE_LAYERS([source._id]);
}

const handleMapUse = (item) => {
  state.map_use_type = item;
  storeMap.SET_CHECKED_MAP_USE(item);

  state.map_measure_type = '';

  if (item !== 'attribute') {
    map.off('click', mapOnClick.value);
    map.getCanvas().style.cursor = 'pointer';
  }

  MEASURE_CLEAR();
};

// 鼠标移除测量
const handleMouseleave = () => {
  if (state.map_measure_type !== '') {
    state.map_use_type = 'measure';
  } else {
    state.map_use_type = '';
  }
};

// 选择测量功能
const handleMapMeasure = (item) => {
  state.map_measure_type = item;
  MEASURE_CLEAR();
  MEASURE_CLEAR_V();

  if (item == '面积测量') {
    MEASURE_AREA_V();
  } else if (item == '长度测量') {
    MEASURE_LINE_V();
  } else if (item == '点坐标测量') {
    MEASURE_POINT();
  } else if (item == '清除测量') {
    MEASURE_CLEAR();
    MEASURE_CLEAR_V();
    setTimeout(() => {
      state.map_measure_type = '';
    }, 8);
    map.getCanvas().style.cursor = 'pointer';
  }
};

const handleCloseQuery = () => {
  state.map_use_type = '';
  storeMap.SET_CHECKED_MAP_USE('');
};

// 获取相关属性数据
const handleQueryInfo = (item, checked_layer, type) => {
  if (type == '属性查询') {
    resultFeatures.value = item;
  }
};

// 功能按钮切换
const handleUseChecked = (type) => {
  useChecked.value = type;
  windowShow.value = false;

  setTimeout(() => {
    windowShow.value = true;
  }, 10);

  mitt.emit('handleItemClose', true);

  if (!['巡护管理'].includes(type)) {
    CLEAR_MAP_LAYER();
  }

  if (type == '实时巡查') {
    // !获取视频列表
  } else {
    clear_map_layer_event();
    checkedVideo.value = {};
    videoDialogVisible.value = false;
  }
};

// 关闭窗口（巡护/事件）
const handleCloseOpen = () => {
  useChecked.value = '';
  windowShow.value = false;
  CLEAR_MAP_LAYER();
  CLEAR_POPUP_MAP();
};

// 清除坐标图层（视频）
const clear_map_layer_event = () => {
  const layerId = layerGroupId.MAP_POINT_LAYER;

  videoPointAll?.value.map((item) => {
    REMOVE_LAYER(layerId + String(item?.channelId));
    REMOVE_MAP_IMG(layerId + String(item?.channelId));
  });
};

// 清除图层数据(巡护人员坐标)
const CLEAR_MAP_LAYER = () => {
  REMOVE_MAP_IMG('point-dot');
  REMOVE_MAP_IMG('user-point-dot');
  CLEAR_POPUP_MAP();

  map?.getStyle()?.layers?.map((item) => {
    if (
      ['MAP_POINT_LAYER', 'MAP_POINT_LAYER_LIGHT', 'MAP_LINE_LAYER', 'MEASURE_POINT'].includes(item?.metadata?.group) &&
      ['source'] in item
    ) {
      REMOVE_LAYER(item?.id);
      REMOVE_MAP_IMG(item?.id);
    }
  });

  map?.setZoom(8);
};

onBeforeUnmount(() => {
  storeMap.RESET();
  window.removeEventListener('resize', resize2D);
  REMOVE_2D_MAP();
  map = null;
});
</script>
<template>
  <div class="data_center_root">
    <div class="map_content">
      <!-- 功能模块 -->
      <div class="use_buttons_left">
        <div
          class="btn_item"
          title="巡护管理"
          :class="useChecked == '巡护管理' ? 'btn_item_checked' : ''"
          @click="
            () => {
              handleUseChecked('巡护管理');
            }
          "
        >
          <img :src="icon_map.XHGL_icon" />
          <p>巡护管理</p>
        </div>
        <div
          class="btn_item"
          title="事件管理"
          :class="useChecked == '事件管理' ? 'btn_item_checked' : ''"
          @click="
            () => {
              handleUseChecked('事件管理');
            }
          "
        >
          <img :src="icon_map.SJGL_icon" />
          <p>事件管理</p>
        </div>
        <div
          class="btn_item"
          title="实时巡查"
          :class="useChecked == '实时巡查' ? 'btn_item_checked' : ''"
          @click="
            () => {
              handleUseChecked('实时巡查');
            }
          "
        >
          <img :src="icon_map.SSXC_icon" />
          <p>实时巡查</p>
        </div>
      </div>

      <!-- 地图操作数据 -->
      <div class="btn_map_use_right">
        <div
          class="use_item"
          :style="{ color: state.map_use_type == 'attribute' ? '#61BA37' : '#5F6477' }"
          @click="handleMapUse('attribute')"
        >
          <p>属性</p>
        </div>
        <ElDivider direction="vertical" />
        <div
          class="use_item"
          :style="{ color: state.map_use_type == 'query' ? '#61BA37' : '#5F6477' }"
          @click="handleMapUse('query')"
        >
          <p>查询</p>
        </div>
        <ElDivider direction="vertical" />
        <div
          class="use_item"
          :style="{ color: state.map_use_type == 'measure' ? '#61BA37' : '#5F6477' }"
          @click="handleMapUse('measure')"
        >
          <p>测量</p>
        </div>
      </div>
      <!-- 测量 -->
      <div v-if="state.map_use_type == 'measure'" class="map_measure" @mouseleave="handleMouseleave()">
        <ElRadioGroup v-model="state.map_measure_type" @change="(e) => handleMapMeasure(e)">
          <ElRadio :label="'点坐标测量'" class="map_measure_item">
            <p>点坐标测量</p>
          </ElRadio>
          <ElRadio :label="'长度测量'" class="map_measure_item">
            <p>长度测量</p>
          </ElRadio>
          <ElRadio :label="'面积测量'" class="map_measure_item">
            <p>面积测量</p>
          </ElRadio>
          <ElRadio :label="'清除测量'" class="map_measure_item">
            <p class="eliminate_p">清除测量</p>
          </ElRadio>
        </ElRadioGroup>
      </div>

      <div id="map-data-center" class="map" />
      <MapPoints />

      <!-- 属性查询 -->
      <MapAttribute
        v-if="state.map_use_type == 'attribute'"
        class="animate__backInDown"
        @handle-close-query="handleCloseQuery"
        @handle-query-info="handleQueryInfo"
      />

      <!-- 巡护管理 -->
      <MapRecordIndex :use-checked="useChecked" :window-show="windowShow" @handle-close-open="handleCloseOpen" />
      <!-- 事件管理 -->
    </div>
  </div>
</template>

<style scoped lang="scss">
.data_center_root {
  position: relative;
  width: 100%;
  height: 100%;
  user-select: none;
  .map_content {
    width: 100%;
    height: 100%;
    .map {
      width: 100%;
      height: 100%;
    }

    .use_buttons_left {
      position: absolute;
      top: 20px;
      left: 27px;
      z-index: 8;

      .btn_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 70px;
        height: 70px;
        margin-bottom: 13px;
        color: #fff;
        background: rgba(24, 33, 47, 0.54);
        border-radius: 10px;
        cursor: pointer;
        p {
          margin-top: 5px;
          font-size: 14px;
          letter-spacing: 1px;
        }
        &:hover {
          background: #377bf0f3;
        }
      }

      .btn_item_checked {
        background: #377bf0f3;
      }
    }

    .btn_map_use_right {
      position: absolute;
      top: 20px;
      right: 34px;
      z-index: 8;
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 336px;
      height: 50px;
      padding: 0 18px;
      color: #5f6477;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 4px;

      .use_item {
        display: flex;
        align-items: center;
        cursor: pointer;

        img {
          width: 18px;
          height: 18px;
        }
        p {
          margin-left: 5px;
          font-size: 18px;
          text-align: left;
          cursor: pointer;
        }
      }
    }
    .map_measure {
      position: absolute;
      top: 80px;
      right: 33px;
      z-index: 99;
      width: 143px;
      height: 185px;
      padding: 18px 32px 10px 18px;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 4px;
      :deep(.el-radio) {
        margin-top: 1px;
        margin-bottom: 6px;
      }
      :deep(.el-radio__label) {
        display: flex;
        align-items: center;
      }

      :deep(.el-radio__input) {
        display: none;
      }
      .map_measure_item {
        img {
          width: 16px;
          height: 16px;
        }
        p {
          margin-left: 10px;
          font-size: 16px;
          text-align: left;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
